using System;
using System.Collections.Generic;
using System.Text;
using ExtendedMvc.Html;

namespace ExtendedMvc.Elements {
	public class ListBox<TModel> : ListBoxBase<ListBox<TModel>, TModel> where TModel : class {
		public ListBox(IModelViewHelper<TModel> helper, string memberName, string id = null) : base(helper, memberName, id) { }
	}

	public abstract class ListBoxBase<T, TModel> : Selection<T, TModel>
		where T : ListBoxBase<T, TModel>
		where TModel : class {
		protected ListBoxBase(IModelViewHelper<TModel> helper, string memberName, string id = null) : base(helper, HtmlTag.Select, (id ?? memberName), memberName, true) { }

		protected override void Prepare() {
			SetAttribute(HtmlAttribute.Multiple, HtmlAttribute.Multiple);
			base.Prepare();
		}

		private void AddOption(StringBuilder sb, KeyValuePair<object, string> option) {
			var item = new Option(option.Key, memberName);
			item.Selected(IsSelected(option.Key));
			sb.Append(item);
		}

		protected override string RenderOptions() {
			if (options == null) throw new ArgumentException("The control must have at least one option defined.", "Options");
			var sb = new StringBuilder();
			foreach (var option in options) AddOption(sb, option);
			return sb.ToString();
		}
	}
}